package live.betterman.api.controller;

import cn.hutool.core.lang.tree.Tree;
import live.betterman.common.model.Result;
import live.betterman.system.model.SysMenu;
import live.betterman.system.model.SysUser;
import live.betterman.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import live.betterman.system.service.SysUserService;
import live.betterman.system.service.SysRoleMenuService;

import java.util.Collection;
import java.util.List;

/**
 * @author: zhudawei
 * @date: 2024/11/4
 * @description: 菜单
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleMenuService roleMenuService;

    @GetMapping("/list")
    public Result<List<SysMenu>> list() {
        List<SysMenu> list = menuService.list();
        return Result.success(list);
    }
    @GetMapping("/tree")
    public Result<List<SysMenu>> tree(){
        List<SysMenu> list = menuService.tree();
        return Result.success(list);
    }
    @GetMapping("/user-tree")
    public Result<List<SysMenu>> userTree() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SysUser user = (SysUser) authentication.getPrincipal();
        Collection<String> userMenuIds = roleMenuService.getUserMenuIds(user.getUserId());
        
        List<SysMenu> allMenus = menuService.tree();
        markMenuVisibility(allMenus, userMenuIds);
        
        return Result.success(allMenus);
    }
    
    private void markMenuVisibility(List<SysMenu> menus, Collection<String> userMenuIds) {
        for(SysMenu menu : menus) {
            menu.setVisible(userMenuIds.contains(menu.getMenuId()));
            if(menu.getChildren() != null) {
                markMenuVisibility(menu.getChildren(), userMenuIds);
            }
        }
    }
    @PostMapping("/add")
    public Result<Boolean> addPermission(@RequestBody SysMenu menu) {
        boolean result = menuService.saveOrUpdate(menu);
        return Result.success(result);
    }

    @PostMapping("/edit")
    public Result<Boolean> editPermission(@RequestBody SysMenu menu) {
        boolean result = menuService.saveOrUpdate(menu);
        return Result.success(result);
    }

    @GetMapping("/current-user-menus")
    public Result<List<SysMenu>> getCurrentUserMenus() {
        SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<SysMenu> menus = menuService.getUserMenus(user.getUserId());
        return Result.success(menus);
    }
}
